// handlers/MarkdownHandler.js
const BaseHandler = require('./BaseHandler');
const fs = require('fs').promises;
const path = require('path');
const MarkdownIt = require('markdown-it');
const markdownItWikiLinkEnhanced = require("../extensions/markdown/MarkdownItWikiLinkEnhanced");
const markdownItLinkOpenEnhanced = require("../extensions/markdown/MarkdownItLinkOpenEnhanced");
const markdownItWikiImageEnhanced = require("../extensions/markdown/MarkdownItWikiImageEnhanced");

class MarkdownHandler extends BaseHandler {
    constructor() {
        super();
        this.md = new MarkdownIt({
            html: true,
            linkify: true,
            typographer: true,
            breaks: true
        })
            .use(require('markdown-it-footnote'))
            .use(require('markdown-it-task-lists'))
            .use(require('markdown-it-mathjax3'));

        // 自定义渲染规则（可选）
        this.configureRenderer();
    }

    configureRenderer() {
        // 示例：为代码块添加语言类
        const defaultRender = this.md.renderer.rules.fence;
        this.md.renderer.rules.fence = (tokens, idx, options, env, self) => {
            const token = tokens[idx];
            const lang = token.info.trim();
            const code = token.content;

            return `<pre><code class="language-${lang}">${this.md.utils.escapeHtml(code)}</code></pre>`;
        };
        this.md.use(markdownItWikiLinkEnhanced);
        this.md.use(markdownItLinkOpenEnhanced);
        this.md.use(markdownItWikiImageEnhanced);
    }

    async handle(req, res, filePath) {
        try {
            // 检查文件是否存在
            if (!await this.fileExists(filePath)) {
                return this.sendError(res, 404, 'Markdown file not found');
            }

            // 读取Markdown内容
            const content = await fs.readFile(filePath, 'utf8');

            // 转换为HTML
            const htmlContent = this.md.render(content);

            // 包装成完整的HTML页面
            const fullHTML = this.wrapInHTMLTemplate(htmlContent, path.basename(filePath));

            // 设置响应头
            res.setHeader('Content-Type', 'text/html; charset=utf-8');
            res.setHeader('Cache-Control', 'public, max-age=300'); // 缓存5分钟

            res.send(fullHTML);

        } catch (error) {
            console.error('Error processing markdown file:', error);
            this.sendError(res, 500, 'Failed to process markdown file');
        }
    }

    wrapInHTMLTemplate(content, title) {
        return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${this.escapeHtml(title.replace('.md', ''))}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            line-height: 1.6; 
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .markdown-body {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1, h2, h3 { 
            margin: 20px 0 10px 0;
            color: #2c3e50;
        }
        h1 { border-bottom: 2px solid #eee; padding-bottom: 10px; }
        p { margin: 10px 0; }
        code { 
            background: #f4f4f4; 
            padding: 2px 6px; 
            border-radius: 3px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
        pre { 
            background: #f8f8f8; 
            padding: 15px; 
            border-radius: 5px; 
            overflow-x: auto;
            margin: 15px 0;
        }
        pre code { background: none; padding: 0; }
        blockquote { 
            border-left: 4px solid #ddd; 
            padding-left: 15px; 
            color: #666;
            margin: 15px 0;
        }
        table { 
            border-collapse: collapse; 
            width: 100%; 
            margin: 15px 0;
        }
        th, td { 
            border: 1px solid #ddd; 
            padding: 8px; 
            text-align: left;
        }
        th { background: #f4f4f4; }
        a { color: #3498db; text-decoration: none; }
        a:hover { text-decoration: underline; }
        img { max-width: 100%; height: auto; }
    </style>
</head>
<body>
    <div class="markdown-body">
        ${content}
    </div>
    
    <script>
        // 为标题添加锚点链接
        document.addEventListener('DOMContentLoaded', function() {
            const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
            headings.forEach(heading => {
                const id = heading.textContent.toLowerCase().replace(/[^a-z0-9]/g, '-');
                heading.id = id;
                
                const anchor = document.createElement('a');
                anchor.href = '#' + id;
                anchor.innerHTML = '🔗';
                anchor.style.marginLeft = '10px';
                anchor.style.textDecoration = 'none';
                anchor.style.opacity = '0.5';
                anchor.addEventListener('mouseenter', () => anchor.style.opacity = '1');
                anchor.addEventListener('mouseleave', () => anchor.style.opacity = '0.5');
                
                heading.appendChild(anchor);
            });
        });
    </script>
</body>
</html>`;
    }

    escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, m => map[m]);
    }
}

module.exports = MarkdownHandler;